package com.ys.controller.api.outer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MenuId;
import com.ys.entity.business.TpBoutique;
import com.ys.entity.business.TpProductActive;
import com.ys.entity.business.TpProductActiveComponent;
import com.ys.entity.flow.YspModel;
import com.ys.entity.purchase.*;
import com.ys.entity.purchase.TcgPurchaseAppointOrderProductComponent;
import com.ys.entity.sys.*;
import com.ys.enume.flow.FlowEnum;
import com.ys.enume.flow.YsProcInstEnum;
import com.ys.mapper.purchase.TcgPurchaseAppointOrderItemMapper;
import com.ys.mapper.purchase.TcgPurchaseAppointOrderProductComponentMapper;
import com.ys.mapper.purchase.TcgPurchaseAppointOrderMapper;
import com.ys.service.bi.BiBusinessFundsService;
import com.ys.service.bi.BiFinancialFundsService;
import com.ys.service.finance.TcwAccountCountForCompanyService;
import com.ys.service.finance.TcwWanliPayoutService;
import com.ys.service.finance.TcwWanliTransferService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.purchase.TcgPurchaseAppointOrderService;
import com.ys.service.purchase.TcgPurchaseAppointOrderService;
import com.ys.service.sys.CommonApiService;
import com.ys.util.CheckUtil;
import com.ys.util.excel.ReadExcel;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.Flow;
import com.ys.vo.R;
import org.apache.poi.hpsf.Decimal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/api/outer/demoXJX")
public class ApiOuterDemoXJXController {
	private static final Logger logger = LoggerFactory.getLogger(ApiOuterDemoXJXController.class);

	@Autowired
	private TcgPurchaseAppointOrderMapper tcgPurchaseAppointOrderMapper;

	@Autowired
	private TcgPurchaseAppointOrderItemMapper tcgPurchaseAppointOrderItemMapper;

	@Autowired
	private TcgPurchaseAppointOrderService tcgPurchaseAppointOrderService;
	
	@Autowired
	private TcgPurchaseAppointOrderProductComponentMapper tcgPurchaseAppointOrderProductComponentMapper;

	@Autowired
	private CommonApiService<TcgPurchaseAppointOrder> commonApiService;

	@Autowired
	private YspTaskService yspTaskService;

	@RequestMapping("/test")
	@ResponseBody
	public R test(HttpServletRequest request, HttpServletResponse response,Map<String, Object> params, String subData) throws Exception{
		try {
			//getRows("http://file.pos.shmtree.com/upload/2021/05/13/150748214.xls", 0);
			//读取本地文件
			FileInputStream fileInputStream = new FileInputStream(new File("C:/Users/Administrator/Desktop/预约采购导入(2).xlsx"));
			List<List<String>> res = ReadExcel.getRowsByInputStream(fileInputStream,0);
			System.out.println("res:\n"+res);
			//将数据分组按照单号
			//新增采购预约主表 根据子件编码去查母件信息和对应的子件信息
			//母表信息
			List<Map<String,Object>> mList = new ArrayList<>();
			//子表信息
			List<Map<String,Object>> sonList = new ArrayList<>();

			for(int i=1;i<res.size();i++) {
				String a1 = res.get(i).get(0);//单号
				String a2 = res.get(i).get(1);//购买方公司名称
				String a3 = res.get(i).get(2);//运营公司编码
				String a4 = res.get(i).get(3);//子件商品编码
				String a5 = res.get(i).get(4);//母件采购数量

				Map<String, Object> mapNew = new HashMap<>();
				mapNew.put("a1", a1);
				mapNew.put("a2", a2);
				mapNew.put("a3", a3);
				mapNew.put("a4", a4);
				mapNew.put("a5", a5);
				sonList.add(mapNew);

			}
				for(int i=0;i<sonList.size();i++){
					if(i==0){
						mList.add(sonList.get(i));
					}else {
						boolean isAdded = false;
						for(Map<String,Object> mItem:mList){
							if(mItem.get("a1").toString().equals(sonList.get(i).get("a1"))){
								isAdded = true;
							}
						}
						if(!isAdded){
							mList.add(sonList.get(i));

						}
					}
				}

			System.out.println("母表:");
			System.out.println(mList);
			System.out.println("子表:");
			System.out.println(sonList);

			for (Map<String,Object> mItem:mList) {
				String a1 = mItem.get("a1").toString();
				String a2 = mItem.get("a2").toString();
				String a3 = mItem.get("a3").toString();
				TbCompanyBankInfo bankInfo = new TbCompanyBankInfo()
						.addLeftJoin("TB_CompanyInfo B on  B.Vid = A.CompanyInfoVid")
						.addField("B.Vname companyVname")
						.addField("B.Tax tax")
						.where("B.Vname = '" + a2 + "'")
						.queryFirst();

				//填入母表信息
				TcgPurchaseAppointOrder entity = new TcgPurchaseAppointOrder();
				String bid = commonApiService.getCommonNextBid(MenuId.TCG_PurchaseAppointOrder);
				entity.setBid(bid);
				entity.setVgsbm(a3);
				entity.setCompanyVid(a2);
				entity.setStatus(1);//状态
				entity.setEffectStock(1);//审批状态
				//获取制单人信息
				TsUserChange tsUserChange = new TsUserChange().setUserId("admin").setStatus(1).queryFirst();
				entity.setCreateChangeId(tsUserChange.getId());//制单人变更信息

				BigDecimal preAccount = BigDecimal.ZERO;//预约采购总额
				//新增母表信息

				//保存子表信息
				for (Map<String, Object> sItem : sonList) {
					if ( sItem.get("a1").toString().equals(a1)) {

						String a4 = sItem.get("a4").toString();
						int a5 = Math.round(Float.parseFloat(sItem.get("a5").toString()));

						TpProductActive tpProductActive=new TpProductActive()
								.addLeftJoin("TP_ProductActiveComponent C ON C.Pcode=A.Code")
								.where("C.code = '" + a4 + "'")
								.queryFirst();
						TpProductActiveComponent tpProductActiveComponent3=new TpProductActiveComponent()
								.addLeftJoin("TP_ProductActive EE ON EE.code=A.Pcode")
								.where("A.code = '" + a4 + "'")
								.queryFirst();
						TcgPurchaseAppointOrderItem sonEntity = new TcgPurchaseAppointOrderItem();

						sonEntity.setPbid(entity.getBid())
								.setStatus(1)
								.setProductCode(tpProductActiveComponent3.getPcode())
								.setProductName(tpProductActive.getName())
								.setCodeMerge(tpProductActive.getCodeMerge())
								.setReserveNumber(a5);
						 int tcgPurchaseAppointOrderItem =new TcgPurchaseAppointOrderItem()
								 .setPbid(entity.getBid())
								 .setProductCode(tpProductActive.getCode())
								 .count();
						 if (tcgPurchaseAppointOrderItem <=0) {
							 tcgPurchaseAppointOrderItemMapper.insert(sonEntity);
						 }

						List<TpProductActiveComponent> tpProductActiveComponent = new TpProductActiveComponent()
								.setPcode(tpProductActive.getCode())
								.addLeftJoin("TP_ProductActive BB ON BB.code=A.Pcode")
								.addField("BB.Code productCode,BB.Name productName,BB.CodeMerge codeMerge")
								.queryList();
						for (int i=0;i<tpProductActiveComponent.size();i++){
							TcgPurchaseAppointOrderProductComponent ProductComponentEntity = new TcgPurchaseAppointOrderProductComponent()
									.addLeftJoin("TP_ProductActiveComponent CC ON CC.Code=A.SubCode")
									.addLeftJoin("TCG_PurchaseAppointOrderItem DD ON DD.Id=A.Pid")
									.where("DD.ProductCode=CC.Pcode")
									.addField("CC.Name subName,CC.SubCodeMerge =A.SubCodeMerge");

							TpProductActiveComponent tpProductActiveComponent1=new TpProductActiveComponent()
									.addLeftJoin("TP_ProductActive EE ON EE.code=A.Pcode")
									.where("A.code = '" + a4 + "'")
									.queryFirst();

							BigDecimal decimal= tpProductActiveComponent1.getNum();
							int tpProductActiveComponent2 = decimal.intValue();
							ProductComponentEntity.setSubCode(a4)
							.setPid(sonEntity.getId())
							.setSubName(tpProductActiveComponent1.getName())
							.setSubCodeMerge(tpProductActiveComponent1.getSubCodeMerge())
							.setSubCode(tpProductActiveComponent1.getCode())
							.setSubBomNumber(tpProductActiveComponent2)
							.setSubBomPrice(tpProductActiveComponent1.getBprice())
							.setSubCodeMerge(a4)
							.setSubReserveNumber(1)
							.setSubTotalPrice(tpProductActiveComponent1.getBprice())
							.setSubCode(a4);

							int tcgPurchaseAppointOrderProductComponent=new TcgPurchaseAppointOrderProductComponent()
									.setPid(sonEntity.getId())
									.setSubCode(a4)
									.count();



							if (tcgPurchaseAppointOrderProductComponent <=0) {
								tcgPurchaseAppointOrderProductComponentMapper.insert(ProductComponentEntity);

								preAccount=preAccount.add(tpProductActiveComponent1.getBprice());
							}
							entity.setPreAccount(preAccount);
						}


					}

				}
				entity.setPreAccount(preAccount);
				tcgPurchaseAppointOrderMapper.insert(entity);


				//生成审批流程
				YsMenu ysMenu = new YsMenu().setId(MenuId.TCG_PurchaseAppointOrder).queryFirst();
				if (ysMenu.getFlowModelId().longValue() != 0L) {
					YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
					String codeModel = yspModel.getCode();
					String createUserId = ShiroUtils.getUserId();
					yspTaskService.init(codeModel, entity.getBid(), createUserId);
				}

			
			}
			return R.ok();
		}catch (Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
			return R.error("操作失败!");
		}

	}

}
